(ns qwiz.views.login
  (:require [noir.response :as resp]
    [noir.session :as session]
    [qwiz.models.model :as mod]
    )
  (:use [noir.core]
    [hiccup.page-helpers]
    [hiccup.form-helpers]
    [hiccup.core]
    [qwiz.gamecore.core]
    ))


(defpartial layout [& content]
  (html5
    [:head
     [:title "Login"]
     (include-css "/css/reset.css")]
    [:body
     [:div#wrapper {:align "center"}
      content]]))

(defpartial user-fields [{:keys [username password]}]
  (label "username" "Username: ")
  (text-field "username" username)
  [:br]
  (label "password" " Password: ")
  (password-field "password" password))

(defpage "/login" {:as user}
  (if (mod/is-user?)
    (resp/redirect "/game")
    (layout
      (form-to [:post "/login"]
        (user-fields user)
        [:br]
        (submit-button "Login")))))

(defpage "/logout" []
  (do
    (unregistered-from-game (mod/me))
    (mod/logout)
    (resp/redirect "/login")))

(defpage [:post "/login"] {:as user}
  ;todo add validation
  (if (= 1 1)
    (let [usr (assoc user :last-chat-update (ref (now)))]
      (println usr "--------------------")
      (mod/login usr)
      (resp/redirect "/game"))
    (resp/redirect "/login")))